/*********************************************************************
 *                                                                   *
 *  Js Css Minifier ( JsCssMin )                                     *
 *  Author: Igor Kanshyn                                             *
 *  Copyright (c) 2009, Igor Kanshyn. All rights reserved.           *
 *                                                                   *
 *  JsCssMin is released under the Apache Software License.          *
 *  See LICENSE.txt for more details.                                *
 *                                                                   *
 *********************************************************************/

package org.grenader.jscssmin.model;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>Product: JsCssMin ( JavaScript and CSS Minifier )<br>
 * Author: Igor Kanshyn (grenader).
 * </p>
 * Date: Apr 25, 2009
 */
abstract public class Resource {

    private String text;
    private String tmpFile;
    private boolean processed;
    private String fileName;

    public Resource(String text) {
        this.text = text;
        this.fileName = extractFileName();
    }

    String extractFileName() {
        Pattern pattern = Pattern.compile(".*" + getFileAttribute() + "=['\"]([^'\"]+)['\"].*", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(text);
        if (matcher.matches() && matcher.groupCount() == 1)
            return matcher.group(1);

        // There is no quotes. So, let's find something wiout blanks
        Pattern patternNoQuotes = Pattern.compile(".*" + getFileAttribute() + "=([^>]+).*", Pattern.CASE_INSENSITIVE);
        Matcher matcherNoQuotes = patternNoQuotes.matcher(text);
        if (matcherNoQuotes.matches() && matcherNoQuotes.groupCount() == 1)
            return matcherNoQuotes.group(1);

        throw new IllegalArgumentException("File name not found. The given text doesn't have required resource info!");
    }


    abstract protected String getFileAttribute();


    abstract public ResourceType getType();

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Resource resource = (Resource) o;

        if (text != null ? !text.equals(resource.text) : resource.text != null) return false;

        return true;
    }

    public void setTmpFile(String tmpFile) {
        this.tmpFile = tmpFile;
    }

    public String getTmpFile() {
        return tmpFile;
    }

    public boolean isProcessed() {
        return processed;
    }

    public void setProcessed(boolean processed) {
        this.processed = processed;
    }

    public String getFileName() {
        return fileName;
    }
}
